# -*- coding: utf-8 -*-
"""
===============================
@Author     : Zuo WenTao
@Time       : 2024/12/31 11:27
@Description: 
@Change     : 
@File       : HeartDetection.py
===============================
"""
import os
import time
import psutil
import threading
from typing import List, Optional


def monitor_script(script_name: str, interval: int = 5, callback: Optional[callable] = None) -> None:
    """
    监控单个 Python 脚本是否在运行，并实现心跳检测。

    :param script_name: 脚本名（如 "DownLoader.py"）
    :param interval: 心跳检测的时间间隔（秒）
    :param callback: 当脚本未运行时的回调函数，可选
    """
    print(f"开始监控脚本：{script_name}")
    while True:
        is_running = False

        for process in psutil.process_iter(attrs=['pid', 'name', 'cmdline']):
            try:
                if 'python' in process.info['name'].lower():
                    cmdline = ' '.join(process.info['cmdline'])
                    print(f"检查进程：{cmdline}")

                    if script_name in cmdline:
                        is_running = True
                        break
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                continue

        if is_running:
            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 脚本 {script_name} 正在运行...")
        else:
            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 脚本 {script_name} 未运行！")
            if callback:
                callback(script_name)

        time.sleep(interval)


def monitor_scripts(script_names: List[str], interval: int = 5, callback: Optional[callable] = None) -> None:
    """
    监控多个 Python 脚本是否在运行，并实现心跳检测。

    :param script_names: 脚本名列表（如 ["DownLoader.py", "DataProcessor.py"]）
    :param interval: 心跳检测的时间间隔（秒）
    :param callback: 当任一脚本未运行时的回调函数，可选
    """
    print(f"开始监控脚本列表：{', '.join(script_names)}")

    threads = []
    for script_name in script_names:
        thread = threading.Thread(target=monitor_script, args=(script_name, interval, callback))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()


def alert_callback(script_name: str):
    print(f"警告！脚本 {script_name} 已停止运行，请检查！")


if __name__ == "__main__":
    # monitor_script("DownLoader.py", interval=10, callback=alert_callback)
    monitor_scripts(
        script_names=["DownLoader.py", "app.py"],
        interval=10,
        callback=alert_callback
    )
